<?php
/*
 * @Descripttion: 
 * @version: 
 * @Author: Lk
 * @Date: 2023-06-26 14:18:21
 * @LastEditors: Lk
 * @LastEditTime: 2023-07-03 15:14:25
 */

namespace app\admin\controller\order;

use app\common\controller\Backend;
use app\common\model\server\Type;
use app\common\model\User;
use app\common\model\user\Enter;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\common\model\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\order\Order;
        $type_list = Type::column('id,title');
        $this->assignConfig("type_list", $type_list);
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user', 'enter'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'title', 'image', 'goods_money', 'employee_id', 'num', 'type', 'complain', 'pay_type', 'point', 'point_deduction', 'vip_deduction', 'pay_money', 'remark', 'status', 'total_money', 'paytime', 'servertime', 'createtime', 'sn', 'canceltime', 'taketime', 'address', 'consignee', 'phone']);
                $row->visible(['user']);
                $row->visible(['enter']);
                $row->getRelation('user')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 派单
     */
    public function send($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $post = request()->post("row/a");
            extract($post);
            if (!isset($ids) || empty($ids)) {
                $this->error('参数错误');
            }
            if (!isset($employee_id) || empty($employee_id)) {
                $this->error('请选择员工');
            }
            if (!$row) {
                $this->error('订单不存在');
            }
            if ($row->status != 10) {
                $this->error('订单状态错误');
            }
            $row->employee_id = $employee_id;
            $res = $row->allowField(true)->save();
            if (!$res) {
                $this->error('发货失败');
            }
            $this->success('发货成功');
        }
        $uids = Enter::where("FIND_IN_SET(:category_id, category_ids)", ['category_id' => $row->category_id])->where('type', '1')->where('state', '1')->column('user_id');
        $data = User::field(['id,nickname,avatar,lat,lng', self::distanceSql($row->lat ?? 0, $row->lng ?? 0)])->where('status', 'normal')->whereIn('id', $uids)->where('employee', 4)->order('distance ASC')->select();

        $this->view->assign('data', $data);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    /**
     * 获取排序sql
     * @param $latitude
     * @param $longitude
     * @return mixed
     */
    private static function distanceSql($latitude, $longitude)
    {
        $field = "(round(6367000 * 2 * asin(sqrt(pow(sin(((lat * pi()) / 180 - ({$latitude} * pi()) / 180) / 2), 2) + cos(({$latitude} * pi()) / 180) * cos((lat * pi()) / 180) * pow(sin(((lng * pi()) / 180 - ({$longitude} * pi()) / 180) / 2), 2)))/1000,2)) AS distance";
        return $field;
    }
    public function complain($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row->complain == '1') {
            $complain = '0';
        } else {
            $complain = '1';
        }
        $res = $row->save(['complain' => $complain]);
        if (!$res) {
            $this->error('失败');
        }
        $this->success('成功');
    }
}
